﻿using UnityEngine;
using System.Collections;

public class PlatformHorizontalMovement : MonoBehaviour
{
	public float speed;
	public float distance;
	public bool rotate;
	public bool invert;
	public float impactSpeed;
	
	private Transform PlatformTransform;
	private bool right;
	private float start;
	private float end;

	private PlayerMovement playerMovement;
	private Vector3 firstVector;
	private Vector3 secondVector;
	private bool isFirst;

	void Start()
	{
		isFirst = true;
		firstVector = secondVector = Vector3.zero;
		playerMovement = GameObject.FindGameObjectWithTag ("Player").GetComponent<PlayerMovement> ();
		right = true;
		PlatformTransform = transform;

		if(rotate)
		{
			start = rigidbody.position.z;
			end = rigidbody.position.z + distance;
			if(invert)
			{
				end = rigidbody.position.z - distance;
			}
		}
		else
		{
			start = rigidbody.position.x;
			end = rigidbody.position.x + distance;
			if(invert)
			{
				end = rigidbody.position.x - distance;
			}
		}
	}
	
	void FixedUpdate()
	{
		UpdateVectors();
		if(invert)
		{
			if(rotate)
			{
				if(right)
				{
					PlatformTransform.position -= Vector3.forward * speed;
					
					if(rigidbody.position.z <= end)
					{
						right = false;
					}
				}
				else 
				{
					PlatformTransform.position += Vector3.forward * speed;
					
					if(rigidbody.position.z >= start)
					{
						right = true;
					}
				}
			}
			else
			{
				if(right)
				{
					// going right
					PlatformTransform.position -= Vector3.right * speed;
					
					if(rigidbody.position.x <= end)
					{
						right = false;
					}
				}
				else 
				{
					// going left
					PlatformTransform.position += Vector3.right * speed;
					
					if(rigidbody.position.x >= start)
					{
						right = true;
					}
				}
			}
		}
		else
		{
			if(rotate)
			{
				if(right)
				{
					PlatformTransform.position += Vector3.forward * speed;
					
					if(rigidbody.position.z >= end)
					{
						right = false;
					}
				}
				else 
				{
					PlatformTransform.position -= Vector3.forward * speed;
					
					if(rigidbody.position.z <= start)
					{
						right = true;
					}
				}
			}
			else
			{
				if(right)
				{
					// going right
					PlatformTransform.position += Vector3.right * speed;
					
					if(rigidbody.position.x >= end)
					{
						right = false;
					}
				}
				else 
				{
					// going left
					PlatformTransform.position -= Vector3.right * speed;
					
					if(rigidbody.position.x <= start)
					{
						right = true;
					}
				}
			}
		}
	}
	
	void UpdateVectors()
	{
		if(!isFirst)
		{
			firstVector = secondVector;
			secondVector = transform.position;			
		}
		else
		{
			firstVector = transform.position;
			isFirst = false;
		}
	}

	void OnTriggerEnter(Collider other)
	{
		playerMovement.AddImpact (secondVector - firstVector, impactSpeed);
	}
}
